﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
using UFSoft.UBF.Util.DataAccess;

namespace ufida.u9.cust.dz.beplugin.Utils
{
    internal class JkyUtils
    {
        private const string VERSION = "v1.0";
        //正式
        private const string APPKEY = "70033959";
        private const string APPSECRET = "ea4c56d185ba40d8abfcba93301b66e9";
      
        //private const string URL = "https://home.es86.com:3032/open/openapi/do";
        //测试
        //private const string APPKEY = "10526885";
        //private const string APPSECRET = "81c0332dc7a94e168504a3c866f79043";
        private const string URL = "https://open.jackyun.com/open/openapi/do";
        /// <summary>
        /// 计算给定字符串的 MD5 值（32 位小写十六进制）
        /// </summary>
        /// <param name="input">待加密字符串</param>
        /// <param name="encoding">字符编码，默认 UTF-8</param>
        /// <returns>MD5 哈希值（小写）</returns>
        public static string GetMd5(string input, Encoding encoding)
        {
            if (input == null) throw new ArgumentNullException(nameof(input));

            if (encoding == null)
                encoding = Encoding.UTF8;

            using (MD5 md5 = MD5.Create())
            {
                byte[] hashBytes = md5.ComputeHash(encoding.GetBytes(input));
                var sb = new StringBuilder(32);
                foreach (byte b in hashBytes)
                    sb.Append(b.ToString("x2"));  // 小写十六进制
                return sb.ToString();
            }
        }

        public static string GetParm(string method, string bizcontent)
        {
            var dic = new SortedDictionary<string, string>();
            dic.Add("method", method);
            dic.Add("appkey", APPKEY);
            dic.Add("version", VERSION);
            dic.Add("contenttype", "json");
            dic.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("bizcontent", bizcontent);

            // 构建待签名的字符串。
            StringBuilder sbSignData = new StringBuilder(APPSECRET);
            foreach (var entry in dic)
            {
                sbSignData.Append(entry.Key + entry.Value);
            }
            sbSignData.Append(APPSECRET);

            string signStr = sbSignData.ToString().ToLower();


            dic.Add("sign", GetMd5(signStr, Encoding.UTF8));

            StringBuilder sbPostData = new StringBuilder();
            foreach (var entry in dic)
            {
              
                //sbPostData.Append("&").Append(entry.Key).Append("=").Append(entry.Value);
                if ("bizcontent".SequenceEqual(entry.Key))
                {
                    sbPostData.Append("&").Append(entry.Key).Append("=").Append(URLEncoder.Encode(entry.Value));
                }
                else
                {
                    sbPostData.Append("&").Append(entry.Key).Append("=").Append(entry.Value);
                }
              //  sbPostData.Append("&").Append(entry.Key).Append("=").Append(entry.Value);
            }

            string postDataStr = sbPostData.ToString().Substring(1);

            return postDataStr;
        }

        public static async Task<WebResult> Post(string method, string bizcontent)
        {
            HttpUtil util = new HttpUtil();

            WebResult result = await util.Post(URL, GetParm(method, bizcontent), "application/x-www-form-urlencoded");
            return result;
        }
    }
}
